<template>
  <div v-loading="loading" element-loading-text="加载中..."
    style="position: relative;display: flex;flex-direction: column;height: 100%;">
    <div class="top">
      <div class="nav">
        <el-tabs class="demo-tabs" v-model="activeName" @tab-change="tabClick">
          <el-tab-pane :name="0">
            <template #label>
              <span>全部工单 ({{ OrderStatusQtyData?.totalOrderQty || 0 }})</span>
            </template>
          </el-tab-pane>
          <!-- <el-tab-pane :name="1">
            <template #label>
              <span class="custom-tabs-label">
                <span>待客服确认</span>
                <span class="icon">{{ OrderStatusQtyData?.waitWerviceConfirm }}</span>
              </span>
            </template>
          </el-tab-pane> -->
          <el-tab-pane :name="1">
            <template #label>
              <span class="custom-tabs-label">
                <span>待平台派单 ({{ OrderStatusQtyData?.waitDispatchOrderQty || 0 }})</span>
              </span>
            </template>
          </el-tab-pane>
          <el-tab-pane :name="3">
            <template #label>
              <span class="custom-tabs-label">
                <span>处理中 ({{ OrderStatusQtyData?.handlerOrderQty || 0 }})</span>
              </span>
            </template>
          </el-tab-pane>
          <el-tab-pane :name="50">
            <template #label>
              <span class="custom-tabs-label">
                <span>待结单 ({{ OrderStatusQtyData?.waitFinishOrderQty || 0 }})</span>
              </span>
            </template>
          </el-tab-pane>
          <el-tab-pane :name="4">
            <template #label>
              <span class="custom-tabs-label">
                <span>已完成 ({{ OrderStatusQtyData?.endOrderQty || 0 }})</span>
              </span>
            </template>
          </el-tab-pane>
          <el-tab-pane :name="5">
            <template #label>
              <span class="custom-tabs-label">
                <span>已取消 ({{ OrderStatusQtyData?.cancelOrderQty || 0 }})</span>
              </span>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="app-container" style="height:100%">
      <div class="app-container-inner" style="display: flex;flex-direction: column;height: 100%;">
        <div class="search flex-align-center">
          <el-select class="input-item mr5" v-model="dateFieldType" placeholder="下单日期" clearable
            @change="getOrderListData()">
            <el-option v-for="item in dateFieldTypeLIst" :key="item.value" :value="item.value" :label="item.title" />
          </el-select>
          <el-select class="input-item mr5" v-model="radio1" placeholder="全部时间" clearable
            @change="radio1 == 1 ? '' : getOrderListData()">
            <el-option v-for="item in timeOptions" :key="item.value" :value="item.value" :label="item.title" />
          </el-select>
          <div class="select-time mr5" v-if="radio1 == 1">
            <el-date-picker v-model="value2" type="daterange" range-separator="~" start-placeholder="开始日期"
              end-placeholder="结束日期" @change="dateChange" value-format="YYYY-MM-DD HH:mm:ss" />
          </div>
          <el-input clearable v-model="input1" placeholder="工单编号" style="width: 160px;" class="input-item mr5"
            @keyup.enter.native="getOrderListData" />
          <el-input clearable v-model="input2" @keyup.enter.native="getOrderListData" placeholder="客户名称/手机号/地址"
            class="input-item mr5" style="width: 170px;" />
          <el-input clearable v-model="input4" @keyup.enter.native="getOrderListData" placeholder="商品品牌/名称/型号"
            class="input-item mr5" style="width: 170px;" />
          <el-input clearable v-model="input5" placeholder="关键字" @keyup.enter.native="getOrderListData"
            class="input-with-select mr5">
            <template #prepend>
              <el-select clearable class="item-select" v-model="field" placeholder="自定义字段" @change="changeinput">
                <el-option v-for="item in fieldOptions" :label="item.name" :value="item.id" />
              </el-select>
            </template>
          </el-input>
          <button class="btn btn-bg1 mr5" @click="getOrderListData">
            <el-icon class="mr5">
              <Search />
            </el-icon>搜索
          </button>
          <button class="btn btn-bg5" @click="clearValue">
            <el-icon class="mr5">
              <RefreshRight />
            </el-icon>重置
          </button>
        </div>
        <div class="btns flex-align-center" style="gap: 5px;">
          <el-button class="btn btn-bg " @click="onNewOrder">
            新建工单
          </el-button>
          <!-- <button class="btn btn-bg5 mr5" @click="assignHandle(1)">
            填写备注
          </button> -->
          <!-- <button class="btn btn-bg3 mr5" @click="assignHandle(2)">
            <span class="iconfont icon-shangjifenpai_line"></span>分派服务商
          </button> -->
          <!-- <button class="btn btn-bg2 mr5" @click="assignHandle(3)">
            <span class="iconfont icon-wancheng"></span>完成
          </button> -->
          <!-- <button class="btn btn-bg5" @click="noteModalVisibleShow">
            服务过程
          </button> -->
          <el-dropdown>
            <button class="btn btn-bg5">
              更多 <el-icon style="margin-left: 5px;"><arrow-down /></el-icon>
            </button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="assignHandle(5)">
                  <i class="fa fa-fax" aria-hidden="true"></i>催单
                </el-dropdown-item>
                <!-- <el-dropdown-item @click="assignHandle(8)"><i class="fa fa-file-archive-o" aria-hidden="true"
                    style="margin-right: 5px;"></i>归档</el-dropdown-item> -->
              </el-dropdown-menu>
              <el-dropdown-item @click="orderExcelImport">
                <i class="fa fa-sign-in" aria-hidden="true"></i>导入</el-dropdown-item>
              <el-dropdown-item @click="exportList"><i class="fa fa-sign-out"
                  aria-hidden="true"></i>导出</el-dropdown-item>
            </template>
          </el-dropdown>
          <button class="btn btn-bg4 mr5" @click="assignHandle(4)">
            取消
          </button>
        </div>
        <!-- 筛选条件 -->
        <div style="width: 100%">
          <ShowTooltip v-if="moduleOptions.length > 0" refName="testName1" className="text-over-tooltip-components"
            :content="`工单类型: ${condition1.map((o) => o.name).join('、')}`" @close="tagClose(1)">
          </ShowTooltip>
          <ShowTooltip v-if="gradeOptions.length > 0" refName="testName3" className="text-over-tooltip-components"
            :content="`等级: ${condition3.map((o) => o.name).join('、')}`" @close="tagClose(3)">
          </ShowTooltip>
          <ShowTooltip v-if="sourceOptions.length > 0" refName="testName4" className="text-over-tooltip-components"
            :content="`工单来源: ${condition4.map((o) => o).join('、')}`" @close="tagClose(4)">
          </ShowTooltip>
          <ShowTooltip v-if="networkOptions.length > 0" @close="tagClose(5)" refName="testName5"
            className="text-over-tooltip-components" :content="`服务商: ${condition5.map((o) => o.name).join('、')}`">
          </ShowTooltip>
          <ShowTooltip v-if="(minCost || minCost == 0) && (maxCost || maxCost == 0)" @close="tagClose(6)"
            refName="testName6" className="text-over-tooltip-components"
            :content="`费用:￥ ${Number(minCost).toFixed(2)}~￥${Number(maxCost).toFixed(2)}`">
          </ShowTooltip>
          <ShowTooltip v-if="(minTime || minTime == 0) && (maxTime == 0 || maxTime) && radio4" @close="tagClose(7)"
            refName="testName7" className="text-over-tooltip-components"
            :content="`服务时长: ${minTime}~${maxTime}${radio4 == 1 ? '小时' : '天'}`">
          </ShowTooltip>
          <ShowTooltip v-if="customerOptions.length > 0" refName="testName8" className="text-over-tooltip-components"
            :content="`客服: ${condition8.map((o) => o.name).join('、')}`" @close="tagClose(8)">
          </ShowTooltip>
        </div>

        <div class="table-list" style="flex: 1;position: relative;">
          <el-table ref="tableList" height="100%" style="position: absolute;" :border="true" stripe resizable
            :data="tableDataList" @selection-change="handleChange" @row-dblclick="goDetail" show-summary
            :summary-method="(val) => getSummaries(val, [1])">
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
            <el-table-column type="selection" width="40" />
            <el-table-column type="index" label="序号" fixed="left" min-width="50" />
            <template v-for="item in OrderListTable">
              <el-table-column show-overflow-tooltip :fixed="item.freezeColumn"
                :align="item.code == 'totalPrice' || item.code == 'orderGoodsQty' || item.code == 'factorySettlementTotalPrice' ? 'right' : 'left'"
                :prop="item.code" :label="item.name" v-if="item.showColumn"
                :min-width="tableColumnWidth[item.code] || 130">

                <template v-if="item.code == 'code'" #default="scope">
                  <!-- <span v-if="scope.row.isRepeatOrder" class="repeat">重</span> -->
                  <!-- <span v-if="scope.row.remindersStatus" class="reminder">催</span> -->
                  <span class="number" @click="goDetail(scope.row)">{{ scope.row.code }}</span>
                </template>

                <template v-if="item.code == 'createTime'" #header>
                  {{ item.name }}
                  <el-popover placement="bottom" :width="250" trigger="click" ref="popoverDom1">
                    <template #reference>
                      <span class="iconfont icon-shaixuan"></span>
                    </template>
                    <div class="select-time" v-if="radio1 == 1">
                      <el-date-picker v-model="value2" type="daterange" range-separator="~" start-placeholder="开始日期"
                        end-placeholder="结束日期" @change="dateChange" value-format="YYYY-MM-DD HH:mm:ss" />
                    </div>
                    <div class="radios">
                      <el-radio-group v-model="radio1" @change="screenDate">
                        <el-radio v-for="item in timeOptions" :key="item.value" :label="item.value">{{ item.title
                          }}</el-radio>
                      </el-radio-group>
                    </div>
                  </el-popover>
                </template>
                <template v-if="item.code == 'module'" #header>
                  {{ item.name }}
                  <el-popover placement="bottom" :width="250" trigger="click" ref="popoverDom2">
                    <template #reference>
                      <span class="iconfont icon-shaixuan"></span>
                    </template>
                    <div class="search-input">
                      <el-input clearable v-model="ordeModule" placeholder="搜索工单类型 按Enter确认" @clear="onclearinput(1)"
                        @keyup.enter.native="confirmSearch(1)" />
                    </div>
                    <div class="checkboxs">
                      <el-checkbox v-model="checkAll1" @change="changeChecked1">全选</el-checkbox>
                      <el-scrollbar class="checkboxs-scrollbar" max-height="350px">
                        <el-checkbox-group v-model="moduleOptions">
                          <el-checkbox v-for="item in modules" :key="item.id" :label="item.id">{{ item.name
                            }}</el-checkbox>
                        </el-checkbox-group>
                      </el-scrollbar>
                    </div>
                  </el-popover>
                </template>
                <template v-if="item.code == 'status'" #default="scope">
                  <el-tag type="warning" v-if="scope.row.status == 1">待派单</el-tag>
                  <el-tag class="ml-2" type="warning" v-if="scope.row.status == 2">待服务商确认</el-tag>
                  <el-tag class="ml-2" type="success" v-if="scope.row.status == 3">处理中</el-tag>
                  <el-tag v-if="scope.row.status == 4">已完成</el-tag>
                  <el-tag type="info" v-if="scope.row.status == 5">已取消</el-tag>
                </template>

                <template v-if="item.code == 'level'" #header>
                  {{ item.name }}
                </template>
                <template v-if="item.code == 'level'" v-slot="scope">
                  <span :style="{ color: scope.row.workLevelColor }">{{ scope.row.workLevel }}</span>
                </template>
                <template v-if="item.code == 'userAddress'" v-slot="i">
                  <span>{{ i.row.province + ' ' + i.row.city + ' ' + i.row.area + ' ' + i.row.town + ' ' + i.row.address
                    }}</span>
                </template>
                <template v-if="item.code == 'totalPrice'" #header>
                  {{ item.name }}
                  <el-popover placement="bottom" :width="250" trigger="click" ref="popoverDom5"
                    @hide="confirmSearch(4)">
                    <template #reference>
                      <span class="iconfont icon-shaixuan"></span>
                    </template>
                    <div class="values flex-justify-between">
                      <el-input clearable v-model="minCost" @input="minCost = minCost.replace(/[^0-9]/g, '')"
                        placeholder="最小值" class="cost-input" />
                      <span>~</span>
                      <el-input clearable v-model="maxCost" @input="maxCost = maxCost.replace(/[^0-9]/g, '')"
                        placeholder="最大值" class="cost-input" />
                    </div>
                  </el-popover>
                </template>
                <template v-if="item.code == 'totalPrice'" v-slot="i">
                  <span>￥{{ (i.row.totalPrice || 0).toFixed(2) }}</span>
                </template>
                <template v-if="item.code == 'factorySettlementTotalPrice'" v-slot="i">
                  <span>￥{{ (i.row.factorySettlementTotalPrice || 0).toFixed(2) }}</span>
                </template>
                <template v-if="item.code == 'serviceProcess'" v-slot="i">
                  <span style="display: flex;align-items: center;gap: 4px;cursor: pointer;width:100%"><el-icon
                      v-if="i.row.serviceProcess" title="查看服务过程" @click="MessageLogFun(i.row)" color="#007cff" link
                      size="16">
                      <ChatLineRound />
                    </el-icon><span style="text-overflow:ellipsis;white-space: nowrap;overflow: hidden;">{{
    i.row.serviceProcess }}</span></span>
                </template>
                <template v-if="item.code == 'network'" #header>
                  {{ item.name }}
                  <el-popover placement="bottom" :width="250" trigger="click" ref="popoverDom6">
                    <template #reference>
                      <span class="iconfont icon-shaixuan"></span>
                    </template>
                    <div class="radios change-radio">
                      <el-radio-group v-model="networkType">
                        <el-radio label="">查询全部</el-radio>
                        <el-radio label="1">已派单</el-radio>
                        <el-radio label="0">未派单</el-radio>
                      </el-radio-group>
                    </div>
                    <div class="checkboxs" v-show="networkType === '1'">
                      <div class="search-input" style="margin-right: 15px;">
                        <el-input clearable v-model="workName" placeholder="搜索服务商名称 按Enter确认"
                          @keyup.enter.native="confirmSearch(5)" @clear="onclearinput(5)" />
                      </div>
                      <el-checkbox v-model="checkAll5" @change="changeChecked5">全选</el-checkbox>
                      <el-scrollbar class="checkboxs-scrollbar" max-height="350px">
                        <el-checkbox-group v-model="networkOptions">
                          <el-checkbox v-for="item in networkSelectData" :key="item.id" :label="item.id"> {{ item.name
                            }}</el-checkbox>
                        </el-checkbox-group>
                      </el-scrollbar>
                    </div>
                  </el-popover>
                </template>
                <template v-if="item.code == 'source'" #header>
                  {{ item.name }}
                  <el-popover placement="bottom" :width="250" trigger="click" ref="popoverDom8">
                    <template #reference>
                      <span class="iconfont icon-shaixuan"></span>
                    </template>
                    <div class="checkboxs">
                      <el-checkbox v-model="checkAll4" @change="changeChecked4">全选</el-checkbox>
                      <el-checkbox-group v-model="sourceOptions">
                        <el-checkbox v-for="item in sources" :key="item.value" :label="item.value">{{ item.title
                          }}</el-checkbox>
                      </el-checkbox-group>
                    </div>
                  </el-popover>
                </template>
                <template v-if="item.code == 'source'" v-slot="i">
                  <span v-for="item in sources" :key="item.value">
                    <span v-if="i.row.source == item.value">{{ item.title }}</span>
                  </span>
                </template>
                <template v-if="item.code == 'emp'" #header>
                  {{ item.name }}
                  <el-popover placement="bottom" :width="250" trigger="click" ref="popoverDom9">
                    <template #reference>
                      <span class="iconfont icon-shaixuan"></span>
                    </template>
                    <div class="search-input">
                      <el-input clearable v-model="customer" placeholder="搜索客服" @clear="onclearinput(8)"
                        @keyup.enter.native="confirmSearch(8)" />
                    </div>
                    <div class="checkboxs">
                      <el-checkbox v-model="checkAll8" @change="changeChecked8">全选</el-checkbox>
                      <el-scrollbar class="checkboxs-scrollbar" max-height="350px">
                        <el-checkbox-group v-model="customerOptions">
                          <el-checkbox v-for="item in customers" :key="item.id" :label="item.id">{{ item.name
                            }}</el-checkbox>
                        </el-checkbox-group>
                      </el-scrollbar>
                    </div>
                  </el-popover>
                </template>
              </el-table-column>
            </template>
            <!-- 自定义字段 -->
            <el-table-column show-overflow-tooltip v-for="(key, index) in arrList" :key="index" min-width="140"
              :label="key.name">
              <template v-slot="i">
                <template v-for="item in i.row.fieldVals">
                  {{ item.id == key.id ? item.val : '' }}
                </template>
              </template>
            </el-table-column>
            <!-- 表单设置 -->
            <el-table-column align="center" fixed="right" width="38">
              <template #header>
                <el-tooltip effect="dark" content="列表设置" placement="top-start">
                  <el-image @click="tableShowSet"
                    style="display: flex;align-items: center;justify-content: center;width: 16px;" :src="setSvg"
                    :size="20"></el-image>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination" style="flex: none;">
          <Pagination ref="pagination" :list_total="totalList" @size-change="getOrderListData"
            @current-change="getOrderListData" />
        </div>
        <AssignDialog :assignAny="assignAny" :assignDialog="assignDialog" :selecttion="selecttion"
          @assign-dialog="assignDialog = false, isbatch = true" :isbatch="isbatch"
          @update-list="getOrderListData(), selecttion = [], arr = []">
        </AssignDialog>
        <!-- 工单导出弹窗 -->
        <el-dialog class="export-dialog" v-model="exportDialog" title="工单导出" width="750px" top="8vh" :draggable="true"
          :destroy-on-close="true" :close-on-click-modal="false" :align-center="true">
          <div class="tips">
            <span>单次最多导出20000条数据</span>
            <span>建议导出当月或三月内的数据，一次性导出数据等待时间过长，建议分批导出</span>
          </div>
          <el-form class="form">
            <el-form-item label="文件名称" class="form-item">
              <el-input v-model="fileName" placeholder="请输入文件名" class="item-input" />
            </el-form-item>
            <el-form-item label="导出数据" class="form-item">
              <el-select v-model="page" placeholder="当前页/全部页" class="item-input">
                <el-option value="当前页">当前页</el-option>
                <el-option value="全部页">全部页</el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div class="card">
            <div class="text">请选择导出字段</div>
            <el-transfer class="transfer-list" v-model="fieldList" filterable target-order="push"
              filter-placeholder="请输入搜索内容" :data="fieldData" :titles="[' ', ' ']">
              <template #default="{ option }">
                <span class="field-name">{{ option.label }}</span>
                <div class="right flex-justify-between">
                  <span class="field-label">{{ option.tip }}</span>
                  <i class="fa fa-bars" @mousedown="domMove($event, option.key)"></i>
                </div>
              </template>
            </el-transfer>
          </div>
          <div class="footer">
            <el-button @click="exportExcelAction" color="#007cff" class="btn_save">导出</el-button>
          </div>
        </el-dialog>
        <!-- 列表设置 -->
        <TableVisibleDialog :type="1" @update-list="getOrderListData(), getOrderListTableFieldList()"
          :dialogTableVisible="dialogTableVisible" @set-table-dialog="dialogTableVisible = $event"></TableVisibleDialog>
        <!-- 服务过程弹窗 -->
        <!-- <ServiceProcess v-model="noteModalVisible" :workIds="arr" @updated="getOrderListData" /> -->
        <!-- 服务过程 -->
        <el-drawer v-model="productDrawerRemark" destroy-on-close :open-delay="100" direction="rtl" show-close
          size="420">
          <template #header>
            <div style="display: flex; gap: 8px; align-items: center; font-size: 14px; color: #303133">
              工单编号:{{ workNo }} <el-icon size="16" style="cursor: pointer" @click="LeaveMessageRef.getList()"
                title="刷新">
                <Refresh />
              </el-icon>
            </div>
          </template>
          <div class="remark_list" v-if="productDrawerRemark" style="width: 100%;">
            <LeaveMessage :workId="workId" ref="LeaveMessageRef"></LeaveMessage>
          </div>
        </el-drawer>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Pagination from '@/components/Pagination/index.vue'
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import type { TabsPaneContext } from 'element-plus'
import { Search, Tickets, PriceTag } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { exportExcel } from '../../../utils/exprotExcel'
import {
  getOrderList, getOrderStatusQty, workModulePageSelect, getOrderListSelectField, getOrderListTableTitleField,
  getOrderListTableField
} from '../../../api/order'
import ServiceProcess from './components/ServiceProcess/ServiceProcess.vue'
import { empPageSelecct } from '../../../api/organize'
import debounce from 'lodash/debounce'
import AssignDialog from './components/AssignDialog.vue'
import TableVisibleDialog from '../../../components/TableVisibleDialog.vue'
import LeaveMessage from "./odetail/components/leaveMessage.vue"
import * as  _ from 'lodash'
import setSvg from "@/assets/order/set.svg";
const tableDataList = ref([])//工单列表数据
const OrderStatusQtyData = ref(null)//工单状态数量数据
const fieldOptions = ref(null)//工单字段下拉列表查询数据列表
let isbatch = ref(true)
const activeName = ref(0)
const router = useRouter()
const loading = ref(false)
const moduleLoading = ref(false)//下拉工单模块loading

const pagination = ref()
const totalList = ref(0)//列表总数量
// 弹窗显示
const assignDialog = ref(false)//分派
const assignAny = ref(null)//分派1 2 3 4

const exportDialog = ref(false) // 导出工单
const page = ref('全部页') // 导出数据页
const fieldList = ref([]) // 导出字段
const fileName = ref('') // 文件名
const format = ref('xlsx') // 文件格式
const columnName = ref([]) // 表头数据
// 服务过程弹窗状态
const noteModalVisible = ref(false)
const noteModalVisibleShow = () => {
  if (arr.value.length == 0) {
    ElMessage({
      message: '请选择要操作的工单',
      type: 'warning',
    })
    return
  }
  noteModalVisible.value = true
}
const fieldData = ref([
  { key: 1, name: 'workNo', label: '工单编号', tip: '系统字段' },
  { key: 2, name: 'createDate', label: '报单时间', tip: '工单自定义字段' },
  { key: 3, name: 'module', label: '工单类型', tip: '系统字段' },
  { key: 4, name: 'status', label: '状态', tip: '系统字段' },
  { key: 5, name: 'proModel', label: '产品型号', tip: '工单自定义字段' },
  { key: 6, name: 'serviceLevel', label: '等级', tip: '系统字段' },
  { key: 7, name: 'cuName', label: '客户名称', tip: '工单自定义字段' },
  { key: 8, name: 'cuPhone', label: '客户电话', tip: '工单自定义字段' },
  { key: 9, name: 'cuAddress', label: '客户地址', tip: '工单自定义字段' },
  { key: 10, name: 'workFee', label: '费用', tip: '系统字段' },
  { key: 11, name: 'netWork', label: '服务商', tip: '系统字段' },
  { key: 12, name: 'processTime', label: '服务时长', tip: '系统字段' },
  { key: 13, name: 'accept', label: '工单来源', tip: '系统字段' },
  { key: 14, name: 'cuService', label: '客服', tip: '工单自定义字段' },
  { key: 15, name: 'updateTime', label: '最后更新时间', tip: '工单自定义字段' },
])
let arrList = ref([])//自定义字段
const keyList = ref([]) // 所有的 key
fieldData.value.forEach((item) => {
  keyList.value.push(item.key)
})
const productDrawerRemark = ref(false)
const LeaveMessageRef = ref()
const workNo = ref('')
const workId = ref('')
const MessageLogFun = (row) => {
  workNo.value = row.code
  workId.value = row.id
  productDrawerRemark.value = true
}
// 搜索栏
const input1 = ref('') // 工单编号
const input2 = ref('') // 搜索客户名称/手机号/地址
const input4 = ref('') // 搜索商品品牌/名称/型号
const input5 = ref('') // 关键字
const field = ref('') // 自定义字段id
const tableList = ref() // 表格Dom

// 弹出层Dom 1-报单时间 2-工单类型 3-产品型号 4-等级 5-费用 6-服务商 7-服务时长 8-工单来源 9-客服
const popoverDom1 = ref()
const popoverDom2 = ref()
const popoverDom5 = ref()
const popoverDom6 = ref()
const popoverDom8 = ref()
const popoverDom9 = ref()

// 表头搜索
const value2 = ref('') // 申请时间
const startTime = ref(null) // 开始日期
const endTime = ref(null) // 结束日期
const ordeModule = ref('') // 工单类型
const orderGrade = ref('') // 等级
const maxCost = ref(null) // 最大值
const minCost = ref(null) // 最小值
const workName = ref('') // 服务商名称
const maxTime = ref(null) // 服务时长最大值
const minTime = ref(null) // 服务时长最小值
const customer = ref('') // 客服

// 筛选 1-报单时间 3-服务商 4-服务时长
const radio1 = ref(null)
// 网点类型：1-已派单，0-未派单，传空值则查询所有
const networkType = ref('')
const radio4 = ref(null)
// 搜索条件显示 1-工单类型 2-报单商品 3-等级 4-工单来源 5-服务商 8-客服 
const condition1 = ref([])
const condition2 = ref([])
const condition3 = ref([])
const condition4 = ref([])
const condition5 = ref([])
const condition8 = ref([])
// 是否全选 1-工单类型 2-报单商品 3-等级 4-工单来源  5-服务商 8-客服
const checkAll1 = ref(false)
const checkAll3 = ref(false)
const checkAll4 = ref(false)
const checkAll5 = ref(false)
const checkAll8 = ref(false)

// 报单时间
const timeOptions = ref([
  { title: '时间区间', value: 1 },
  { title: '今天', value: 2 },
  { title: '本周', value: 3 },
  { title: '本月', value: 4 },
  { title: '过去三个月', value: 5 },
])
const dateFieldType = ref(1)//时间类型
const dateFieldTypeLIst = ref([
  { title: '报单日期', value: 1 },
  { title: '完工日期', value: 2 },
  { title: '结算日期', value: 3 }
])
// 工单类型
const moduleOptions = ref([])
const modules = ref(null)
// 等级
const gradeOptions = ref([])
const grades = ref(null)

// 服务商
const networkOptions = ref([])
const networkSelectData = ref([])

// 工单来源
const sourceOptions = ref([])
const sources = ref([
  { title: '平台系统报单', value: 1 },
  { title: '扫码报单', value: 2 },
  { title: '小程序报单', value: 3 },
  { title: 'APP报单', value: 4 },
  { title: 'Excel导入报单', value: 5 },
  { title: '品牌商家建单', value: 6 },
  { title: '平台代商家报单', value: 7 },
  { title: '品牌商家Excel导入', value: 8 },
  { title: '乐开伙伴云', value: 9 }
])
// 表格每一列的宽度
const tableColumnWidth = {
  code: '150', // 工单编号
  createTime: '128', // 报单时间
  factory: '100', // 商家名称
  factorySettlementTotalPrice: '100', // 商家结算总价
  networkSettlementTotalPrice: '120', // 服务商结算总价
  status: 120, // 工单状态
  module: '170', // 工单类型
  userName: 90, // 客户姓名
  userPhone: '110', // 客户手机号
  userAddress: '200', // 客户地址
  orderGoods: '200', // 报单商品
  network: '160', // 服务商
  engineer: '80', // 工程师
  reservationDate: '128', // 预约时间
  serviceTime: '180', // 节点时效
  emp: '90', // 客服
  totalPrice: '120', // 工单总费用
  source: '110', // 工单来源
  updateTime: 130,
  orderFinishTime: 130
}
// 合计
const getSummaries = (param, arr = []) => {
  const { columns, data } = param
  const sums: string[] = []
  arr = [1]
  let isShow = true
  OrderListTable.value.map(o => {
    if (o.code == 'factorySettlementTotalPrice' || o.code == 'orderGoodsQty') {
      arr.push(o.sort + 2)
      if (o.code == 'orderGoodsQty') {
        isShow = false
      } else {
        isShow = true
      }
    }
  })
  columns.forEach((column, index) => {
    if (arr.includes(index) && (index == 1 || index == 0)) {
      sums[index] = '合计'
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (!values.every((value) => Number.isNaN(value))) {
      if (arr.includes(index)) {
        if (column.property == "orderGoodsQty") {
          sums[index] = `${values
            .reduce((prev, curr) => {
              const value = Number(curr)
              if (!Number.isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)}`
        } else {
          sums[index] = `￥${values
            .reduce((prev, curr) => {
              const value = Number(curr)
              if (!Number.isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            .toFixed(2)}`
        }
      }
    } else {
      sums[index] = ''
    }
  })
  return sums
}
// 客服
const customerOptions = ref([])
const customers = ref(null)

// 工单类型下拉数据
const getworkModulePageSelect = async (val) => {
  let data = {
    "limit": 0,
    "keyword": val,
    "page": 0
  }
  moduleLoading.value = true
  await workModulePageSelect(data).then((res) => {
    modules.value = []
    if (res.data.success) {
      modules.value = res.data.data.rows
    }
    moduleLoading.value = false
  })
}

// 工单客服组下拉列表查询
const getworkTeamPageSelect = async (val) => {
  let data = {
    "limit": 0,
    "name": val,
    "page": 0
  }
  loading.value = true
  customers.value = []
  await empPageSelecct(data).then((res) => {
    if (res.data.success) {
      customers.value = res.data.data.rows
    }
    loading.value = false
  })
}

// 导航切换
const tabClick = (tab: TabsPaneContext) => {
  activeName.value = Number(tab)
  getOrderListData()
}

// 获取表格选中的数据
const selecttion = ref([])
const arr = ref([])
const handleChange = (val: any) => {
  if (val.length != 0) {
    arr.value = []
    val.forEach((item) => {
      arr.value.push(item.id)
    })
  }
}
// 重置
const clearValue = () => {
  dateFieldType.value = 1
  radio1.value = null
  input1.value = ''
  input2.value = ''
  input4.value = ''
  input5.value = ''
  field.value = ''
  value2.value = ''
  startTime.value = null
  endTime.value = null
  maxTime.value = null
  minTime.value = null
  minCost.value = null
  maxCost.value = null
  radio4.value = null
  checkAll1.value = false
  checkAll3.value = false
  checkAll4.value = false
  checkAll5.value = false
  checkAll8.value = false
  ordeModule.value = ''
  orderGrade.value = ''
  customer.value = ''
  moduleOptions.value = []
  gradeOptions.value = []
  sourceOptions.value = []
  customerOptions.value = []
  networkType.value = ''
  networkOptions.value = []
  getworkModulePageSelect('')
  getOrderListData()
}
// 搜索显示tag 1工单类型 2报单商品 3等级 4工单来源 5-服务商 6费用 7服务时长 8-客服
const tagClose = (n: number) => {
  switch (n) {
    case 1:
      moduleOptions.value = []
      condition1.value = []
      break;
    case 2:
      condition2.value = []
      break;
    case 3:
      gradeOptions.value = []
      condition3.value = []
      break;
    case 4:
      sourceOptions.value = []
      condition4.value = []
      break;
    case 5:
      networkOptions.value = []
      condition5.value = []
      networkType.value = ''
      break;
    case 6:
      minCost.value = null
      maxCost.value = null
      break;
    case 7:
      minTime.value = null
      maxTime.value = null
      radio4.value = null
      break;
    case 8:
      customerOptions.value = []
      condition8.value = []

      break;
  }
}
const changeinput = () => {
  input5.value = ''
}

// 跳转到创建工单页面
const onNewOrder = () => {
  router.push('/new')
}

// 1-备注  3-批量完成工单 4-批量取消工单 5催单
const assignHandle = (n: number, val = null) => {
  if (!(n == 1 || n == 4 || n == 5)) {
    ElMessage({
      type: 'warning',
      message: '暂不开放此功能，正在维护升级中，敬请期待...'
    })
    return
  }
  if (val) {
    selecttion.value = [val]
  } else {
    selecttion.value = arr.value
  }
  if (selecttion.value.length == 0) {
    ElMessage({
      message: '请选择要操作的工单',
      type: 'warning',
    })
    return
  }
  assignAny.value = n
  assignDialog.value = true
}
// 导入工单
const orderExcelImport = () => {
  router.push('orderExcelImport')
}
// 导出工单数据
const exportList = () => {
  ElMessage({
    message: '正在维护升级中，敬请期待...',
    type: 'warning'
  })
  // fileName.value = ''
  // fieldList.value = []
  // columnName.value = []
  // exportDialog.value = true
}

// 拖动排序
const domMove = (obj, key) => {
  let index
  fieldList.value.forEach((item, i) => {
    if (item == key) {
      index = i
    }
  })
  let changeItem = fieldList.value[index] // 移动的项
  let dom = obj.target
  //算出鼠标相对元素的位置
  dom.style.cursor = 'move'
  let reY = obj.clientY - dom.offsetTop
  // 鼠标按下事件，松开后不再移动
  document.onmouseup = (e) => {
    document.onmousemove = null
    document.onmouseup = null
    //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
    let top = e.clientY - reY
    let num = Math.floor(top / 39) // 移动的位置
    if (num > 0) {
      // 下移
      fieldList.value.splice(index, 1)
      fieldList.value.splice(index + num, 0, changeItem)
    } else {
      // 上移
      num = Math.abs(num)
      fieldList.value.splice(index, 1)
      fieldList.value.splice(index - num, 0, changeItem)
    }
  }
}

// 确定导出
const exportExcelAction = () => {
  if (fileName.value == '') {
    ElMessage({
      message: '请输入文件名',
      type: 'warning',
    })
    return
  }
  if (page.value == '') {
    ElMessage({
      message: '请选择要导出的数据',
      type: 'warning',
    })
    return
  }
  if (fieldList.value.length == 0) {
    ElMessage({
      message: '请选择要导出的字段',
      type: 'warning',
    })
    return
  }
  fieldList.value.forEach((item) => {
    if (keyList.value.indexOf(item) != -1) {
      columnName.value.push({
        name: fieldData.value[keyList.value.indexOf(item)].name,
        label: fieldData.value[keyList.value.indexOf(item)].label,
      })
    }
  })
  exportExcel({
    column: columnName.value,
    data: tableDataList.value,
    filename: fileName.value,
    format: format.value,
    autoWidth: true,
  })
  ElMessage({
    message: '导出成功',
    type: 'success',
  })
  exportDialog.value = false
}

// 查看工单详细
const goDetail = (val: any) => {
  router.push('/order/odetail/' + val.id)
}

// 报单时间变化时
const dateChange = (val: any) => {
  if (val) {
    // popoverDom1.value.hide()
    startTime.value = val[0]
    endTime.value = val[1]
  } else {
    startTime.value = null
    endTime.value = null
  }
  getOrderListData()
}

// 筛选报单时间
const screenDate = (value: any) => {
  if (value != 1) {
    popoverDom1.value.hide()
    getOrderListData()
  }
}

// 1-工单类型 2-报单商品 3-等级 5-服务商 8-客服
const onclearinput = (n: number) => {
  switch (n) {
    case 1:
      getworkModulePageSelect('')
      break;
    case 8:
      getworkTeamPageSelect('')
      break;
  }

}
//@input搜索 1-工单类型 2-报单商品 3-等级 4-费用 5-服务商 6-服务时长  8-客服
const confirmSearch = debounce((n: number) => {
  if (n == 1) {
    checkAll1.value = false
    getworkModulePageSelect(ordeModule.value)
  }
  if (n == 4) {
    if (minCost.value && maxCost.value) {
      minCost.value = Number(minCost.value)
      maxCost.value = Number(maxCost.value)
    }
    if (minCost.value || maxCost.value) {
      if (!maxCost.value) {
        return
      }
      if (!minCost.value) {
        minCost.value = 0
      }
      getOrderListData()
    }
  }
  if (n == 6) {
    if (minTime.value || maxTime.value) {
      if (!maxTime.value) {
        return
      }
      if (!minTime.value) {
        minTime.value = 0
      }
    }
    getOrderListData()
  }
  if (n == 8) {
    checkAll8.value = false
    getworkTeamPageSelect(customer.value)
  }
}, 0)

//全选@change 1-工单类型 2-报单商品 3-等级 4-工单来源  5-服务商 8-客服
const changeChecked1 = (val) => {
  if (modules.value.length > 0) {
    modules.value.map(o => {
      if (val) {
        moduleOptions.value = [...moduleOptions.value, o.id]
      }
      else {
        moduleOptions.value = moduleOptions.value.filter(i => i != o.id)
      }
    })
  }

}
const changeChecked4 = (val) => {
  if (val) {
    sourceOptions.value = sources.value.map(o => {
      return o.value
    })
  } else {
    sourceOptions.value = []
  }
}

const changeChecked5 = (val) => {
  if (networkSelectData.value.length > 0) {
    networkSelectData.value.map(o => {
      if (val) {
        networkOptions.value = [...networkOptions.value, o.id]
      } else {
        networkOptions.value = networkOptions.value.filter(i => i != o.id)
      }
    })

  }
}
const changeChecked8 = (val) => {
  if (customers.value.length > 0) {
    customers.value.map(o => {
      if (val) {
        customerOptions.value = [...customerOptions.value, o.id]
      } else {
        customerOptions.value = customerOptions.value.filter(i => i != o.id)
      }
    })

  }
}
// 监听勾选 1-工单类型 2-报单商品 3-等级 4-工单来源 5-客服 8-服务商
watch(moduleOptions, (val) => {
  moduleOptions.value = val
  checkAll1.value = modules.value.every(o => {
    return moduleOptions.value.includes(o.id)
  })
  modules.value.filter(o => {
    if (moduleOptions.value.includes(o.id)) {
      if (condition1.value.length > 0) {
        if (!condition1.value.some(i => i.id == o.id)) {
          condition1.value.push(o)
        }
      } else {
        condition1.value.push(o)
      }
    }
  })
  let arr = condition1.value
  condition1.value = []
  moduleOptions.value.map(o => {
    arr.filter(i => {
      if (i.id == o) {
        condition1.value.push(i)
      }
    })
  })
  getOrderListData()
})
watch(gradeOptions, (val) => {
  gradeOptions.value = val
  checkAll3.value = grades.value.every(o => {
    return gradeOptions.value.includes(o.id)
  })
  grades.value.filter(o => {
    if (gradeOptions.value.includes(o.id)) {
      if (condition3.value.length > 0) {
        if (!condition3.value.some(i => i.id == o.id)) {
          condition3.value.push(o)
        }
      } else {
        condition3.value.push(o)
      }
    }
  })
  let arr = condition3.value
  condition3.value = []
  gradeOptions.value.map(o => {
    arr.filter(i => {
      if (i.id == o) {
        condition3.value.push(i)
      }
    })
  })

  getOrderListData()
})
watch(sourceOptions, (val) => {
  sourceOptions.value = val
  checkAll4.value = sources.value.every(o => {
    return sourceOptions.value.includes(o.value)
  })
  condition4.value = []
  sources.value.filter(o => {
    if (sourceOptions.value.includes(o.value)) {
      condition4.value.push(o.title)
    }
  })
  getOrderListData()
})
watch(customerOptions, (val) => {
  customerOptions.value = val
  checkAll8.value = customers.value.every(o => {
    return customerOptions.value.includes(o.id)
  })
  customers.value.filter(o => {
    if (customerOptions.value.includes(o.id)) {
      if (condition8.value.length > 0) {
        if (!condition8.value.some(i => i.id == o.id)) {
          condition8.value.push(o)
        }
      } else {
        condition8.value.push(o)
      }
    }
  })
  let arr = condition8.value
  condition8.value = []
  customerOptions.value.map(o => {
    arr.filter(i => {
      if (i.id == o) {
        condition8.value.push(i)
      }
    })
  })

  getOrderListData()
})

// 获取自定义字段下拉
const getOptions = async () => {
  await getOrderListSelectField().then((res) => {
    fieldOptions.value = res.data.data.rows
  })
}

//获取工单列表
const getOrderListData = _.debounce(async () => {
  let itmeType = null
  if (radio1.value) {
    // 筛选条件 时间类型
    itmeType = radio1.value
  }
  let tab = null
  if (activeName.value === 0) {//判断是切换为全部工单
    tab = null
  } else {
    tab = activeName.value
  }
  // 服务时长类型
  if (!(radio4.value && maxTime.value)) {
    radio4.value = null
    maxTime.value = null
    minTime.value = null
  }
  let data: any = {
    createOrderEmp: '',//报单人
    dateFieldType: dateFieldType.value,
    "dateType": itmeType,//报单时间类型
    "fieldId": field.value,//工单字段名
    "fieldSearch": input5.value,//工单字段搜索关键词
    "goodsSearch": input4.value,//	商品搜索：品牌/产品名称/产品型号
    "limit": pagination.value.size,//每页显示数量
    "maxPrice": maxCost.value,//费用最大值
    "minPrice": minCost.value,//费用最小值
    "moduleIds": moduleOptions.value,//工单模块ID
    "orderEndTime": endTime.value,//报单结束时间
    "orderStartTime": startTime.value,//报单开始时间
    "orderNo": input1.value,//工单单号
    "orderUserSearch": input2.value,// 工单客户搜索关键词：客户名称/客户手机号/客户地址
    "page": pagination.value.current,//当面页码
    "sources": sourceOptions.value,//工单来源
    "status": tab,//工单状态
    // "empIds": customerOptions.value,//客服ID
    // "networkIds": networkOptions.value,//	服务区域ID
    // "maxServiceTime": Number(maxTime.value),//最大服务时长值
    // "minServiceTime": minTime.value,//最小服务时长值
    // "serviceTimeType": radio4.value,//服务时长类型
    // "workLevelIds": gradeOptions.value,//等级ID
  }
  loading.value = true
  await getOrderList(data).then(res => {
    if (res.data.success) {
      tableDataList.value = res.data.data.rows
      totalList.value = Number(res.data.data.total)
      getOrderStatusQtyData()
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 4000,
        offset: 200
      })
    }
    loading.value = false
  })
}, 0)
// 获取工单列表状态数量
const getOrderStatusQtyData = async () => {
  await getOrderStatusQty().then(res => {
    if (res.data.success) {
      OrderStatusQtyData.value = res.data.data.row
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 4000,
        offset: 200
      })
    }
  })
}
const getOrderListTableTitleFieldList = async () => {
  await getOrderListTableTitleField().then(res => {
    if (res.data.success) {
      arrList.value = res.data.data.rows
    }

  })
}
// // 获取工单列表表头字段
const dialogTableVisible = ref(false)
const OrderListTable = ref([])
const getOrderListTableFieldList = () => {
  getOrderListTableField(1).then(res => {
    if (res) {
      OrderListTable.value = res.data.data.rows
    }
  })
}
// 点击列表设置
const tableShowSet = () => {
  dialogTableVisible.value = true
}

onMounted(() => {
  new Promise(() => {
    getOrderListData()
    getOptions()
    getOrderListTableTitleFieldList()
    getworkModulePageSelect('')
    getOrderListTableFieldList()

  })
})
</script>

<style scoped lang="scss">
@import './index';
</style>
